import { knowledgeApi } from '/api/konwledge'
import { mallApi } from '/api/mall'
import { userApi } from '/api/user'
import { getUser } from '/store/actions'
import { getServer, onNews } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event } from '/utils'

Page({
  data: {
    navigationHeight: 0,
    list: [] as DomoFeed[],
    knowLedgeList: [] as any[],
    access: GlobalData.access,
    noMore: false,
    page: 1,
    isLastPage: false,
    type: '' /** 删除订单的角色 */,
    id: 0 /** 4销售订单 5兑换订单 */,
    /** 是否是销售订单列表 */
    isSalesOrder: false,
    show: false,
    currencyName: GlobalData.currencyName,
    currentTab: 0,
    KnowledgeisLastPage: false,
    knowLedagepage: 0,
    knowledge: {} as any,
    mall_commodities: {} as any,
    /** 提现余额显示开关 */
    paytoast: false,
    user: {} as DomoUser,
    remove: false,
    /** 提现按钮显示开关 */
    status: false,
    /** 是商家显示商家模板 */
    shopkeer: true,
    /** 是知识作者，显示知识模板 */
    kownledgeAutor: true,
  },
  onLoad(query: any) {
    $event.on('mallOrderChange', this, () => {
      this.getData()
    })
    const abilities: any = GlobalData.userAbilities
    const user = wx.getStorageSync(`${getServer()}/logged`).data || {}
    const { shopkeeper, ability_name } = GlobalData.mall
    // 是购买的订单
    const isSalesOrder = +query.id === 4
    const isShopper =
      isSalesOrder ||
      (shopkeeper === 'verification' && user && user.verification && user.verification.state === 1
        ? true
        : shopkeeper === 'ability' &&
          abilities &&
          abilities.some((v: any) => v.name === ability_name))

    const author = GlobalData.knowledge.author
    const authorAbility = GlobalData.knowledge.ability_name
    const isKownledgor =
      isSalesOrder ||
      (author === 'verification' && user && user.verification && user.verification.state === 1
        ? true
        : author === 'ability' && abilities && abilities.some((v: any) => v.name === authorAbility))

    this.setData({
      id: +query.id,
      isSalesOrder,
      type: isSalesOrder ? 'shopkeeper' : 'user',
      currencyName: GlobalData.currencyName,
      navigationHeight: GlobalData.navigationHeight,
      access: GlobalData.access,
      status: GlobalData.wallet.cash.status,
      user: getUser(),
      shopkeer: isShopper,
      kownledgeAutor: isKownledgor,
      // 如果不是商城商家，且不是销售订单
      currentTab: isSalesOrder && !isShopper ? 1 : 0,
    })
    $event.on('after:confirm', this, (id) => {
      this.changeData(id)
    })
    $event.on('after:mall_commodities', this, (id) => {
      const {
        data: { list },
      } = this
      list.map((i: any) => {
        i.commodity_id == id ? (i.comment_id = 1) : ''
      })
      this.setData({ list })
    })
    if (query.number) {
      userApi.removeUnreadTips('mall_selling_commodity').then(() => {
        $event.emit('after:notification')
      })
      this.setData({
        remove: true,
      })
    }
    this.getData()
  },

  async onPullDownRefresh() {
    await this.getData()
    wx.stopPullDownRefresh()
  },
  // true 是销售订单
  isSaleOrder() {
    return +this.data.id == 4
  },
  /**
   * 处理数据，计算状态显示
   * @param list 数据
   * @returns 处理后的数据
   */
  handleData(list: any[]) {
    return list.map((orderInfo: any) => {
      if (orderInfo.parentOrder) {
        orderInfo.sub_orders.forEach((i: any) => {
          i.status_text = this.orderStatusResolve(i, this.isSaleOrder())
        })
      } else {
        orderInfo.status_text = this.orderStatusResolve(orderInfo, this.isSaleOrder())
        if (orderInfo.status_text === '等待发货') {
          orderInfo.status_text = '已支付'
        }
      }
      return orderInfo
    })
  },
  async getData() {
    const list = await this.fetchList(1)
    if (this.data.currentTab === 0) {
      this.setData({
        list: this.handleData(list),
        show: true,
      })
    } else {
      this.setData({
        knowLedgeList: list,
        show: true,
      })
    }
  },
  async onReachBottom() {
    if (
      (this.data.currentTab === 0 && this.data.isLastPage) ||
      (this.data.currentTab === 1 && this.data.KnowledgeisLastPage)
    ) {
      wx.showToast({
        title: '已没有更多了',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    wx.showLoading({
      title: '加载中',
    })
    let list = await this.fetchList(
      this.data.currentTab == 0 ? this.data.page + 1 : this.data.knowLedagepage + 1,
    )
    if (this.data.currentTab === 0) {
      list = this.handleData(list)
      this.setData({
        list: [...this.data.list, ...list],
      })
    } else {
      this.setData({
        knowLedgeList: [...this.data.knowLedgeList, ...list],
      })
    }

    wx.hideLoading()
  },
  async fetchList(page: number) {
    const pay_status = this.isSaleOrder() ? '2' : `0,1,2,3,4`
    const list =
      this.data.currentTab === 0
        ? await mallApi.getMallOrders({
            role: this.data.type,
            page: page,
            date_key: 'created_at',
            pay_status: pay_status,
            with: 'subOrders',
            user_trashed: 'without',
            shop_trashed: 'without',
            // eslint-disable-next-line @typescript-eslint/ban-ts-ignore
            // @ts-ignore
            subOrders: 1,
            noGroupBy: 1,
          })
        : await knowledgeApi.getKonwledgeOrder({
            role: this.isSaleOrder() ? 'author' : this.data.type,
            page: page,
            date_key: 'created_at',
            pay_status: pay_status,
            with: 'author,knowledge',
          })
    const isLastPage =
      list.meta.last_page === list.meta.current_page || list.meta.last_page < list.meta.current_page
    if (this.data.currentTab === 0) {
      this.setData({
        page,
        isLastPage,
      })
    } else {
      this.setData({
        knowLedagepage: page,
        KnowledgeisLastPage: isLastPage,
      })
    }
    return list.data
  },
  async toDetail(e: WechatMiniprogram.CustomEvent) {
    if (this.data.id == 4) {
      try {
        await onNews(['{{NEW_ORDER_KEY}}'])
      } catch (error) {
        wx.showToast({ title: '请配置正确的订阅消息key，具体位置在package.json', icon: 'none' })
      }
    }
    const index = e.currentTarget.dataset.index
    wx.navigateTo({
      url: `/mall/orderDetail/orderDetail?index=${index}&id=${this.data.id}&orderId=${this.data.list[index].id}`,
    })
  },
  onDownload() {
    $event.emit('download')
  },
  /** 跳转商品/知识详情 */
  toProductDetail(e: WechatMiniprogram.BaseEvent) {
    const data = e.currentTarget.dataset as { id: number; orderId?: number; deleted_at?: string }
    if (data.deleted_at) {
      wx.showToast({
        title: '该商品已下架',
        icon: 'none',
      })
      return
    }
    wx.navigateTo({
      url:
        this.data.currentTab === 0
          ? `/mall/detail/detail?commodityId=${data.id}&orderId=${data.orderId}`
          : `/index/knowledge/detail/detail?id=${data.id}`,
    })
  },
  /** 根据ID找出对应数据替换 */
  changeData(id: any) {
    const {
      data: { list },
    } = this
    list.map((i: any) => {
      i.id == id ? (i.receipt_at = 1) : ''
    })
    this.setData({ list })
  },
  // tab切换
  async clickTab(e: WechatMiniprogram.BaseEvent) {
    if (this.data.currentTab === e.currentTarget.dataset.current) return
    if (this.data.id == 4) {
      try {
        await onNews(['{{NEW_ORDER_KEY}}'])
      } catch (error) {
        wx.showToast({ title: '请配置正确的订阅消息key，具体位置在package.json', icon: 'none' })
      }
    }
    this.setData({
      currentTab: +e.currentTarget.dataset.current,
    })
    wx.startPullDownRefresh()
    if (this.data.remove) {
      userApi.removeUnreadTips('selling_knowledge').then(() => {
        $event.emit('after:notification')
        this.setData({
          remove: false,
        })
      })
    }
  },
  /** 提现 */
  operation() {
    wx.navigateTo({
      url: '/mine/withdrawContainer/withdrawContainer',
    })
    // this.show()
  },
  show() {
    this.setData({
      paytoast: true,
    })
  },
  close() {
    this.setData({
      paytoast: false,
    })
  },
  //点评
  comment(e: WechatMiniprogram.BaseEvent) {
    const item = e.currentTarget.dataset.item
    this.setData({
      knowledge: item,
    })
    wx.showActionSheet({
      itemList: ['文字', '图片', '视频'],
      success(res) {
        switch (res.tapIndex) {
          case 0:
            wx.navigateTo({
              url: `/pages/publish/publish?about=knowledge&id=${item.id}`,
            })
            break
          case 1:
            wx.navigateTo({
              url: `/pages/publish/publish?type=image&about=knowledge&id=${item.id}`,
            })
            break
          case 2:
            wx.navigateTo({
              url: `/pages/publish/publish?type=video&about=knowledge&id=${item.knowledge_id}`,
            })
            break
        }
      },
    })
  },
  /**
   * 冻结状态：0-正常，1-冻结中（申诉中），2-冻结中（后台受理申诉），3-处理中（后台处理申诉），4-已关闭（申诉完成，已关闭），5-被驳回（后台驳回申诉）
   * 按照excel订单状态判断：https://docs.qq.com/sheet/DUGlZTFlDQ25qRXdK
   * 状态：
   *     先判断冻结字段，再判断status的状态
   *     如果是已冻结、冻结被驳回、冻结已受理，就直接显示冻结情况
   *     如果是处理中，显示“申诉已处理+status的状态”
   *     如果是已关闭，显示“status的状态”
   * @param  shopkeeper true 代表商家从销售订单入口查看
   */
  orderStatusResolve(orderInfo: any, shopkeeper?: boolean) {
    const { locked = 0, status } = orderInfo // refund_count:已使用次数
    let title = '' // 状态文本

    // 公共按钮：付款、修改地址、取消、确认收货、删除
    // 以下为单个订单的按钮显示控制

    // 正常订单的状态判断
    const statusResolve = () => {
      switch (status) {
        case 'PS_UNPAID':
          title = '待付款'
          break
        case 'PS_SUCCEEDED':
          title = '等待发货'
          break
        case 'PS_EXPIRED':
          title = '支付超时'
          break
        case 'PS_CANCEL':
          title = '订单已取消'
          break
        case 'EP_SEND':
          title = '已发货'
          break
        case 'EP_SIGNED':
          title = '已收货'
          break
        case 'EP_TIMEOUT':
          title = shopkeeper ? '已收货' : '签收超时已收货'
          break
        case 'RF_APPLY':
          title = shopkeeper ? '买家已申请退款中' : '申请退款中'
          break
        case 'RF_AGREE':
          title = shopkeeper ? '同意退款' : '商家已同意退款'
          break
        case 'RF_REFUSE':
          title = shopkeeper ? '驳回退款' : '退款申请被驳回，退款失败'
          break
        case 'RF_FINISH':
          title = '退款成功'
          break
        case 'RF_OTHER':
          title = '三方退款成功'
          break
        case 'RF_FAILED':
          title = '退款失败'
          break
        case 'RT_APPLY':
          title = shopkeeper ? '买家已申请退货' : '申请退货中'
          break
        case 'RT_REFUND':
          title = shopkeeper ? '已拦截发货，直接退款' : '商家已拦截退货，直接退款'
          break
        case 'RT_AGREE':
          title = shopkeeper ? '等待买家发货' : '商家已同意退货'
          break
        case 'RT_REFUSE':
          title = shopkeeper ? '已驳回退货申请' : '退货申请被驳回，退货失败'
          break
        case 'RT_SENDOUT':
          title = shopkeeper ? '买家已发货' : '已发货，等待商家收货'
          break
        case 'RT_TIMEOUT':
          title = shopkeeper ? '买家超时发货，订单已冻结' : '超时发货，订单已冻结'
          break
        case 'RT_CONFRIM_REFUND':
          title = shopkeeper ? '已收货确认退款' : '商家已收货'
          break
        case 'RT_OTHER':
          title = '三方退款成功'
          break
        case 'RT_FINISH':
          title = '退款成功'
          break
        case 'RT_FAILED':
          title = '退款失败'
          break
        case 'RT_CONFRIM_TIMEOUT':
          title = shopkeeper ? '签收超时已收货' : '已收货'
          break
        case 'RT_CONFRIM_NEGOTIATE':
          title = '协商退款'
          break
        case 'RT_NEGO_APPLY':
          title = shopkeeper ? '买家已发送协商退款申请' : '协商退款申请中'
          break
        case 'RT_NEGO_AGREE':
          title = shopkeeper ? '同意协商退款' : '商家已同意协商退款'
          break
        case 'RT_NEGO_REFUSE':
          title = shopkeeper ? '驳回协商退款申请' : '协商退款申请被驳回'
          break
        case 'RT_NEGO_FINISH':
          title = '退款成功'
          break
        case 'RT_NEGO_OTHER':
          title = '三方退款成功'
          break
        case 'RT_NEGO_FAILED':
          title = '退款失败'
          break
        case 'CLOSE':
          title = '已关闭'
          break
        case 'COMMENTED':
          title = '已评价'
          break
      }
    }
    // 冻结订单
    switch (locked) {
      case 1: // 已冻结
        title = '已冻结'
        break
      case 2: // 冻结已受理
        title = '申诉已受理'
        break
      case 3: // 处理中。用户可操作
        statusResolve()
        title = '申诉已处理，' + title
        break
      case 5: // 驳回。用户可操作
        title = '申诉被驳回'
        break
      default:
        statusResolve()
        break
    }
    return title
  },
})
